
#include "comm.hpp"

int main()
{
    // 1、创建公共的key值
    key_t k = ftok(PATH_NAME, PROJ_ID);
    if (k < 0)
    {
        Log("client:ftok failure!", Error)<< " clinet key: " << k << endl;
        exit(1);
    }
    Log("client:ftok success", Debug) << " clinet key: " << k << endl;


    //2、获取共享内存
    int shmid = shmget(k, SHM_SIZE, IPC_CREAT);//若创建的共享内存在底层存在，则获取并返回
        if( shmid < 0)
    {
        Log("client: get shm failure!", Error) << " the shmid:" << shmid << endl;
        exit(2);
    }
    Log("client: get shm success", Debug) << " the shmid:" << shmid << endl;


    //3、建立映射（关联）
    char* shmaddr = (char*)shmat(shmid, nullptr, 0);
    Log("client: attach shm success", Debug) << " the shmaddr: "<< shmaddr << endl;
    

    //4、进行通信：写端，输入数据
    //4.1、以写的方式打开管道文件
    int fd = OpenFIFO(FIFO_NAME,WRITE);

    //4.2、通讯：将数据写入共享内存
    while(true)
    {
        int n = read(0, shmaddr, SHM_SIZE-1);
        if( n > 0)
        {
            shmaddr[n-1] = 0;//键盘读取数据输入共享内存，最后一位为\n
            //4.3、写端：向名命管道中发送指令(内容随机),告知读端数据输入完毕
            Signal(fd);
            Log("写端：数据输入完成:>", Notice);

            if(strcmp(shmaddr,"quit")==0) break; //用于结束写端
    
        }
    }
    //4.3、完成通讯，关闭名命管道（见下述）


    //5、取消映射（去关联）
    int ret = shmdt(shmaddr);
    assert( ret != -1);
    Log("client: detach shm success", Debug) << " the ret: " << ret << endl;


    //6、server中做了处理，此处不用删除共享内存
    closeFIFO(fd);//关闭名命管道
    
    return 0;
}